<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <!-- 添加角色 -->
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table :data="rolesList"  border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" v-slot="{row}">
          <el-row v-for="(item1, i1) in row.children" :key="item1.id" :class="['bdbottom', i1===0? 'bdtop':'', 'vcenter']">
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag size="min" closable @close="removeRightById(row, item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级三级权限 -->
            <el-col :span="19">
              <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2===0? '':'bdtop', 'vcenter']">
                <el-col :span="6">
                  <el-tag size="min" type="success" closable @close="removeRightById(row, item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(row, item3.id)">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="角色操作" v-slot="{row}" width="290px">
           <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
           <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
           <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(row)">分配权限</el-button>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
      :default-checked-keys="defkeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights" >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色列表
      rolesList: [],
      // 控制分配权限对话框显隐藏
      setRightDialogVisible: false,
      // 权限数据
      rightsList: [],
      // 树形控件的绑定对象
      treeProps: {
        // 名称
        label: 'authName',
        // 数据
        children: 'children'
      },
      // 默认选中的权限的id值数组
      defkeys: [],
      // 当前即将分配权限的角色id，保存下来后面方便获取
      roleId: ''
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.rolesList = res.data
      console.log(res.data)
    },
    // 根据ID删除对应权限
    async removeRightById (role, rightId) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了删除！')
      const { data: res } = await this.axios.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败!')
      // 操作后刷新
      // this.getRolesList() 这样会使展开列表初始化而闭合 (所以可以直接赋当前数据到页面)
      role.children = res.data
    },
    // 展示分配权限对话框
    async showSetRightDialog (role) {
      // 获取这个角色id以备后面取用
      this.roleId = role.id
      // 获取所有权限数据列表(三级权限种类是一样的)
      const { data: res } = await this.axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败！')
      this.rightsList = res.data
      // 获取三级节点id数据
      this.getLeafKeys(role, this.defkeys)
      // 展开tree列表
      this.setRightDialogVisible = true
    },
    // 通过递归形式获取三级权限id
    getLeafKeys (node, arr) {
      // 如果当前节点是三级节点，则添加id进数组
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是三级就递归获取三级节点id，保存到arr中
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框关闭事件
    setRightDialogClosed () {
      // 清空，防止数组数据混乱
      this.defkeys = []
    },
    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 要求以逗号分隔的权限id列表，所以是字符串
      const idStr = keys.join(',')
      // 不能直接获取角色id，需要先保存再去取this.roleId
      const { data: res } = await this.axios.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message('分配权限失败！')
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  },
  created () {
    this.getRolesList()
  },
  components: {}
}
</script>

<style lang="scss" scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
// 角色列表纵向居中对齐
.vcenter {
  display: flex;
  align-items: center;
}
</style>
